package net.esj.basic.dao.jdbc.jpa.support;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import net.esj.basic.dao.jdbc.jpa.ConnectionProvider;
import net.esj.basic.dao.jdbc.jpa.Session;
import net.esj.basic.dao.jdbc.jpa.SessionFactory;
import net.esj.basic.dao.jdbc.jpa.TableBeanMapping;

public abstract class SessionFactorySupport implements SessionFactory{
	protected ConnectionProvider connectionProvider;
	protected Map<Class,TableBeanMapping> mappingMap = new HashMap();
	public Session openSession() {
		Session s = createSession();
		s.setSessionFactory(this);
		s.setConnection(this.connectionProvider.getConnection());
		return s;
	}
	public ConnectionProvider getConnectionProvider() {
		return connectionProvider;
	}
	public void setConnectionProvider(ConnectionProvider connectionProvider) {
		this.connectionProvider = connectionProvider;
	}
	public TableBeanMapping getTableBeanMapping(Class entityType) {
		Set<Class> keySet = mappingMap.keySet();
		for (Class klass : keySet) {
			if(klass.isAssignableFrom(entityType))return mappingMap.get(klass);
		}
		return null;
	}
	protected abstract Session createSession();
	public void registerEntityType(Class entityType){
		TableBeanMapping mapping = TableBeanMapping.parseEntityType(entityType);
		this.mappingMap.put(entityType, mapping);
	}
}
